/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-28 19:07:29
 * @LastEditors: YangJianFei
 * @LastEditTime: 2024-10-09 09:42:24
 * @FilePath: \yt_devop_app\lib\pages\devices\device_tab\device_detail\electric_meter\electric_meter_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

import 'electric_meter_model.dart';

class ElectricMeterController extends BaseDetailController {
  DeviceServices deviceServices = Get.find();

  ///
  UseSubsribe subsribe = UseSubsribe();

  Stream<Map<String, dynamic>>? dataStream;

  StreamSubscription? dataSubscription;

  /// 设备详情
  DeviceModel? deviceModel;

  /// 设备id;
  late int deviceId;

  List<MeterGridModel> models = [];

  Map<String, dynamic> dataSource = {};

  List<PopupMenuItem> actionList = [];

  /// 远程控制指令
  Map remoteControlMap = {};

  /// 配置信息
  Map configMap = {};

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {
    dataSubscription?.cancel();
    subsribe.closeListen();
  }

  init(DeviceModel model) async {
    await getOssPhysicalModel(deviceId);
    dataSubscription = subsribe
        .start([deviceId], true)
        .stream
        .asBroadcastStream()
        .listen((event) {
          dataSource.addAll(event);
          update();
        });
  }

  Future getOssPhysicalModel(int deviceId) =>
      Configs.httpClient.requestWithLoading(
        () async {
          var result = await DeviceServices()
              .getDeviceNewProperty({'deviceId': deviceId, 'platform': 1});

          for (var res in result['data']) {
            if ((res['id'] == 'runningData' || res['id'] == 'deviceDetail') &&
                res['children'].isNotEmpty) {
              List groupMapList = res['children'] ?? [];
              if (groupMapList.first['showType'] ==
                  DeviceModelShowType.grid.value) {
                models = groupMapList
                    .map((e) => MeterGridModel.fromJson(e))
                    .toList();
              } else {
                models = [
                  MeterGridModel.fromJson({
                    'children': groupMapList,
                    'name': ResKey.deviceMainsLoad.tr
                  })
                ];
              }

              update();
            } else if (res['id'] == 'remoteControl') {
              remoteControlMap = filterByAuthority(res) ?? {};
              var pass = remoteControlMap.keys.isNotEmpty;

              if (pass) {
                actionList.add(generatePopItem(
                    Image.asset(
                      ImageAssets.iconRemoteControl,
                      fit: BoxFit.fill,
                    ),
                    ResKey.remoteControll.tr,
                    1));
              }
            } else if (res['id'] == 'config') {
              configMap = filterByAuthority(res) ?? {};
              var pass = configMap.keys.isNotEmpty;

              if (pass) {
                actionList.add(generatePopItem(
                    Image.asset(
                      ImageAssets.iconSetting,
                      fit: BoxFit.fill,
                    ),
                    ResKey.parameterSets.tr,
                    0));
              }
            }
          }
        },
        showLoading: false,
      );

  PopupMenuItem generatePopItem(Widget icon, String title, value) {
    return PopupMenuItem(
      value: value,
      enabled: false,
      child: Row(
        children: [
          icon,
          Gaps.hGap10,
          Text(
            title,
            style: TextStyles.f14,
          ),
        ],
      ),
    );
  }

  Future<bool> toService(value) async {
    Get.back();

    if (value == 0) {
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceId,
        'page': configMap,
        'title': ResKey.parameterSets.tr
      });
    } else if (value == 1) {
      /// 远程控制
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceId,
        'page': remoteControlMap,
        'title': ResKey.remoteControll.tr
      });
    }
    return true;
  }

  /// 过滤掉没有“detail”权限的项
  Map? filterByAuthority(Map page) {
    if (FuncUtils.isPassTargetAuthority(page['authority'],
        permissionSource: UserEntityManager().webPermission)) {
      List children = page['children'] ?? [];
      List filtedChildren = [];
      for (var i = 0; i < children.length; i++) {
        var map = filterByAuthority(children[i]);
        if (map != null) {
          filtedChildren.add(map);
        }
      }
      if ((!FuncUtils.isListEmpty(children) &&
              FuncUtils.isListEmpty(filtedChildren)) ||
          FuncUtils.isListEmpty(children) &&
              page['type'] != 'property' &&
              page['type'] != 'component') {
        /// 下级都没有权限，则移除父级
        return null;
      } else {
        page['children'] = filtedChildren;
      }

      return page;
    } else {
      return null;
    }
  }
}
